package com.example.weatherreport.ui.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.weatherreport.receiver.NetStatusReceiver;
import com.example.weatherreport.R;
import com.example.weatherreport.service.WeatherQualityService;
import com.example.weatherreport.util.SystemProgramUtils;
import com.example.weatherreport.bean.Weather;
import com.example.weatherreport.net.callback.WeatherCallback;
import com.example.weatherreport.net.WeatherHelper;
import com.example.weatherreport.util.FileProviderUtils;

import java.io.File;

import static androidx.core.content.PermissionChecker.PERMISSION_GRANTED;
import static com.example.weatherreport.receiver.NetStatusReceiver.NETSTATUS_INAVAILABLE;
import static com.example.weatherreport.receiver.NetStatusReceiver.NETSTATUS_MOBILE;

/**
 * 首页
 */
public class HomeActivity extends AppCompatActivity {
    private static final String TAG = "HomeActivity";

    /**
     * 城市名称控件
     */
    private TextView mTvCity;

    /**
     * 城市当前的天气 控件
     */
    private TextView mTvWeather;

    /**
     * 网络状态广播器
     */
    private NetStatusReceiver mNetStatusReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        initViews();
        initService();
        initReceiver();
    }

    /**
     * 初始化View
     */
    private void initViews() {
        mTvCity = findViewById(R.id.tv_city);
        mTvWeather = findViewById(R.id.tv_weather);

        //查询按钮
        Button btnQuery = findViewById(R.id.btn_query);
        btnQuery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //查询天气情况
                queryWeather();
            }
        });

        Button btnSelectImg = findViewById(R.id.btn_select_img);
        btnSelectImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //需要先检查有关的权限
                checkPermissions();
            }
        });

        Button btnStopService = findViewById(R.id.btn_stop_service);
        btnStopService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopService();
            }
        });
    }

    /**
     * 初始化后台查询Service
     */
    private void initService() {
        Intent service = new Intent(this, WeatherQualityService.class);
        startService(service);
    }

    /**
     * 关闭Service
     */
    private void stopService() {
        Intent service = new Intent(this, WeatherQualityService.class);
        stopService(service);
    }

    /**
     * 初始化广播器
     */
    private void initReceiver() {
        mNetStatusReceiver = new NetStatusReceiver();
        mNetStatusReceiver.setNetStateListener(new NetStatusReceiver.INetStatusListener() {
            @Override
            public void getNetState(int netStatus) {
                Log.i(TAG, "getNetState: " + netStatus);
                if (netStatus == NETSTATUS_INAVAILABLE) {
                    Toast.makeText(HomeActivity.this, "网络未连接", Toast.LENGTH_SHORT).show();
                    showErrorDialog();
                } else if (netStatus == NETSTATUS_MOBILE) {
                    Toast.makeText(HomeActivity.this, "网络处于移动网络", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(HomeActivity.this, "网络处于Wifi网络", Toast.LENGTH_SHORT).show();
                }
            }
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mNetStatusReceiver, intentFilter);
    }

    private void checkPermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA}, 1);
        } else {
            SystemProgramUtils.camera(HomeActivity.this, new File(Environment.getExternalStorageDirectory().getPath() + "/bg.jpg"));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        Uri fileUri;
        File outputFile = new File(Environment.getExternalStorageDirectory().getPath() + "/bg_out.jpg");//裁切后输出的图片
        switch (requestCode) {
            case SystemProgramUtils.REQUEST_CODE_CAMERA:
                //拍照完成，进行图片裁切
                File file = new File(Environment.getExternalStorageDirectory().getPath() + "/bg.jpg");
                fileUri = FileProviderUtils.uriFromFile(HomeActivity.this, file);
                SystemProgramUtils.cutCrop(HomeActivity.this, fileUri, outputFile);
                break;
            case SystemProgramUtils.REQUEST_CODE_PHOTO:
                //相册选择图片完毕，进行图片裁切
                if (data == null || data.getData() == null) {
                    return;
                }
                fileUri = data.getData();
                SystemProgramUtils.cutCrop(HomeActivity.this, fileUri, outputFile);
                break;
            case SystemProgramUtils.REQUEST_CODE_CUT:
                //图片裁切完成，显示裁切后的图片
                try {
                    Uri uri = Uri.fromFile(outputFile);
                    Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
                    ((ImageView) findViewById(R.id.iv_img)).setImageBitmap(bitmap);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        checkPermissions();
    }

    /**
     * 显示网络错误
     */
    private void showErrorDialog() {
        //创建一个 AlertDialog.Builder 对象
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        //给对话框添加title
        builder.setTitle("网络状况");
        //给对话框添加内容
        builder.setMessage("您的网络未连接");
        builder.setPositiveButton("设置网络", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                startActivity(intent);
            }
        });
        builder.setCancelable(false);
        builder.show();
    }

    /**
     * 查询天气并且显示
     */
    private void queryWeather() {
        WeatherHelper.queryWeather(new WeatherCallback() {
            @Override
            public void onResult(final Weather weather) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTvCity.setText(weather.getCity());
                        mTvWeather.setText(weather.getWea());
                    }
                });
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mNetStatusReceiver);
    }
}
